<template>
  <div>
    <!--
          action: 设置图片上传的接口地址
          http-request	覆盖默认的上传行为，可以自定义上传的实现
       -->
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :http-request="uploadImg"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-progress
      v-if="percent>0&&percent<100"
      :text-inside="true"
      :stroke-width="26"
      :percentage="percent"
    />
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDIRM3g7KL8h3A3jBONRGrENHxQfg9XjFb',
  SecretKey: 'HMG0XqvmQt9D3g50mKfppbAVcXEk6FBu'
})
export default {
  data() {
    return {
      imageUrl: '',
      percent: 0
    }
  },
  methods: {
    // 自定义上次函数
    uploadImg(data) {
      //   console.log(27, data)
      // data.file 就是我们上次的图片文件对象
      const that = this
      cos.uploadFile({
        Bucket: 'hr-84-1315674516', /* 填写自己的bucket，必须字段 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: Date.now().toString(), /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: data.file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: function(progressData) {
          console.log('图片上传进度', progressData)
          that.percent = progressData.percent * 100
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)
          that.imageUrl = 'http://' + data.Location
        }
      })
    }
  }
}

</script>
  <style scoped lang="scss">
  // ::v-deep 样式穿透
    ::v-deep .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    ::v-deep .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    ::v-deep .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    ::v-deep .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  </style>

